import React, { useEffect, useRef, useState } from 'react'
import useGetTableData from '@/hooks/useGetTableDataV2'
import SearchForm from '@/components/QsfCustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import { useIndexColumns, useArrivalColumns } from './TableColumns'
import DeskMerLogo from '@/assets/images/desk_mer.png'
import { PurchaseArrivalTrackingVOV2 as ITableData, DashBoardTimeAchieveSimpleVO, TrackWorkBenchTodoVO } from './types'
import CustomTable from '@/components/QsfCustomTable'
import { useNavigate } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import { searchConfig, useEditConfig } from './FormConfig'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import './index.less'
import useCachePage from '@/hooks/useCachePage'
import { getRecentMonths, importNotification } from '@/utils/util'
import { Form, message, Modal, Space, Button, Tooltip, Select, Empty, notification } from 'antd'
import BoxGroup from './components/BoxGroup'
import ProcessCircle from './components/ProcessCircle'
import ProcessPie from './components/ProcessPie'
import ReturnTimeTable from './components/ReturnTimeTable'
import DetailContainer from '@/components/DetailContainer'
import CircleRate from './components/CirecleRate'
import { getProductClassConfigByType } from '@/api/goods'
import useSearchUser from '@/hooks/useSearchUser'
import useSearchSpu from '@/hooks/useSearchSpu'
import CheckBoxBatch from './components/CheckBoxBatch'
import TimeLineScroll from '@/components/TimeLineScroll/TimeLineScroll'
import useModal from '@/hooks/useModal'
import { EditFormVertical } from '@/components/CustomForm'
import PermissionButton from '@/components/PermissionButton'
import { DownOutlined, ImportOutlined, UpOutlined } from '@ant-design/icons'
import {
  countProduceScheduleExpReq,
  getAnnualDeliveryRateReq,
  getCountArrivalTrackingReq,
  getYearTimeAchieveDashboardReq,
  saveScheduleExtraReq,
  scheduleDefendOverviewReq,
  getDashboardArrivalTrackingV2,
  trackWorkbenchConfirmTime,
  trackWorkbenchHasRead,
  trackWorkbenchTodo,
} from '@/api/desk'
import dayjs from 'dayjs'
import {
  batchImportDeliveryTime,
  getReserveInvoiceWithPurchase,
  importPurchaseProduceSchedule,
  updatePurchaseInfo,
  updateScheduleTime,
} from '@/api/purchase'
import ImportFileModal from '@/components/ImportFileModal'
import { applicationTypeEnum, IMPORT_FILE_ENUM } from '@/constant'
import { TwoDateVerifyCanEqual } from '@/utils/validator'
import ToDoList from './components/ToDoList'
const Index: React.FC = () => {
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormUpload] = useForm()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const userInfo = useAppSelector((state) => state.user.user_info)
  const selectedId = useRef(null)
  const { setCachePage, getCachePage } = useCachePage()
  const { UserOptions, setUserOptions, handleSearchUser } = useSearchUser('id', { roleIds: ['61', '64'] }, true)
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [selectedRows, setselectedRows] = useState<ITableData[]>([])
  const {
    UserOptions: UserOptionsW,
    handleSearchUser: handleSearchUserW,
    setUserOptions: setUserOptionsW,
  } = useSearchUser('workId', { roleIds: ['61', '64'] }, true)
  const [exportLoading, setexportLoading] = useState(false)
  const [progressCollapsed, setProgressCollapsed] = useState(false)
  const [isUploadFileShow, setisUploadFileShow] = useState<boolean>(false)
  const [expandedRowKeys, setexpandedRowKeys] = useState<any[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const isLeader = buttonCodeList.includes('DeskMerLeader')
  const [leaderSelectWorkId, setleaderSelectWorkId] = useState(() => {
    const cacheData = getCachePage()
    return cacheData?.RootSelect || null
  })
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const [tempCode, setTempcode] = useState<
    IMPORT_FILE_ENUM.PURCHASEW_PROCESS_IMPORT | IMPORT_FILE_ENUM.PURCHASEW_DELIVERYTIME_IMPORT
  >(IMPORT_FILE_ENUM.PURCHASEW_DELIVERYTIME_IMPORT)
  const [countArrivalTracking, setcountArrivalTracking] = useState<{
    arrivedNum: number
    shouldArriveNum: number
    percent: number
  }>({
    arrivedNum: 0,
    shouldArriveNum: 0,
    percent: 0,
  })
  const [scheduleDefendOverview, setscheduleDefendOverview] = useState<{
    maintainCount: number
    unMaintainCount: number
    percent: number
  }>({
    maintainCount: 0,
    unMaintainCount: 0,
    percent: 0,
  })
  const [countProduceScheduleExp, setCountProduceScheduleExp] = useState<{
    lessExpNum: number
    moreExpNum: number
    totalNum: number
  }>({
    lessExpNum: 0,
    moreExpNum: 0,
    totalNum: 0,
  })
  const [AnnualDeliveryRate, setAnnualDeliveryRate] = useState('0%')
  const {
    UserOptions: UserOptionsSelf,
    setUserOptions: setUserOptionsSelf,
    handleSearchUser: handleSearchUserSelf,
  } = useSearchUser('id', { roleIds: ['61', '64'] }, true)
  const { SupplierOption, setSupplierOption, handleSearchSupplier } = useSearchSupplier('supplierId')
  const { SpuOptions, handleSearchSpu, setSpuOptions } = useSearchSpu('spuCode')
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [dashBoardData, setdashBoardData] = useState<DashBoardTimeAchieveSimpleVO[]>([])
  const [tableData, settableData] = useState<ITableData[]>([])
  const weekOrMonth = useRef<'week' | 'month'>('week')
  const [workToDoMap, setworkToDoMap] = useState<TrackWorkBenchTodoVO>({})
  const defaultDateRange = getRecentMonths('YYYY-MM-DD')
  const addModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      reload()
    },
  })
  const editTimeModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      reload()
    },
    onFail: (res) => {
      if (res.code === 820000 && res.failInfo) {
        const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
          return <div key={item}>{item}</div>
        })
        notification.open({
          type: 'warning',
          message: res?.msg,
          description: failInfo,
        })
      }
    },
  })
  const TrackingArrivedModal = useModal()

  useEffect(() => {
    getProductClassConfig()
    handleCacheData()
  }, [])
  useEffect(() => {
    console.log(112233)
    getDashBoardData()
  }, [leaderSelectWorkId])
  const getDashBoardData = () => {
    getScheduleDefendOverviewReq()
    getCountProduceScheduleExp()
    getCountArrivalTracking()
    getAnnualDeliveryRate()
    getYearTimeAchieveDashboard()
  }
  const getScheduleDefendOverviewReq = async () => {
    const res = await scheduleDefendOverviewReq({
      trackOrderPersonWorkId: isLeader ? leaderSelectWorkId : userInfo?.workId,
    })
    setscheduleDefendOverview({
      maintainCount: res?.data?.maintainCount,
      unMaintainCount: res?.data?.unMaintainCount,
      percent: res?.data?.percent,
    })
    await getTrackWorkbenchTodoReq(res?.data?.unMaintainCount)
  }
  const getTrackWorkbenchTodoReq = async (unMaintainCount: string | number) => {
    const res = await trackWorkbenchTodo({
      trackOrderPersonWorkId: isLeader ? leaderSelectWorkId : userInfo?.workId,
    })
    setworkToDoMap(res?.data ? { ...res.data, productionplan: unMaintainCount || 0 } : {})
  }
  const getCountProduceScheduleExp = async () => {
    const res = await countProduceScheduleExpReq({
      trackOrderPersonWorkId: isLeader ? leaderSelectWorkId : userInfo?.workId,
    })
    setCountProduceScheduleExp({
      totalNum: Number(res?.data?.totalNum) || 0,
      lessExpNum: Number(res?.data?.lessExpNum) || 0,
      moreExpNum: Number(res?.data?.moreExpNum) || 0,
    })
  }
  const getCountArrivalTracking = async () => {
    const paramsData = getRangeByType(weekOrMonth.current)
    const res = await getCountArrivalTrackingReq({
      trackOrderPersonWorkId: isLeader ? leaderSelectWorkId : userInfo?.workId,
      ...paramsData,
    })
    const isZero = Number(res?.data?.shouldArriveNum) + Number(res?.data?.arrivedNum) == 0 || res?.data?.arrivedNum == 0
    const percent = isZero
      ? 0
      : ((res?.data?.arrivedNum / (Number(res?.data?.shouldArriveNum) + Number(res?.data?.arrivedNum))) * 100).toFixed(
          2,
        )
    setcountArrivalTracking({
      arrivedNum: res?.data?.arrivedNum,
      shouldArriveNum: res?.data?.shouldArriveNum,
      percent: Number(percent),
    })
  }
  const getAnnualDeliveryRate = async () => {
    const res = await getAnnualDeliveryRateReq({
      trackOrderPersonWorkId: isLeader ? leaderSelectWorkId : userInfo?.workId,
    })
    setAnnualDeliveryRate(res?.data?.percent || '0%')
  }
  const getYearTimeAchieveDashboard = async () => {
    const res = await getYearTimeAchieveDashboardReq<DashBoardTimeAchieveSimpleVO>({
      trackOrderPersonWorkId: isLeader ? leaderSelectWorkId : userInfo?.workId,
      year: dayjs().year(),
    })
    setdashBoardData(res?.data || [])
  }
  const impactDeliveryTime = Form.useWatch('impactDeliveryTime', addModal?.form)
  const { tableProps, params, search, reset, reload } = useGetTableData<ITableData>(getDashboardArrivalTrackingV2, {
    form: form,
    immediatelySend: false,
    defaultFieldsParams: {
      officialOrderTimeStart: defaultDateRange,
      CheckBoxKeys: { statuses: [2] },
    },
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqestParams) => {
      const { CheckBoxKeys, ...reqParams } = reqestParams
      return {
        ...reqParams,
        ...CheckBoxKeys,
        onlySeeProduceScheduleExp:
          CheckBoxKeys?.onlySeeProduceScheduleExp && CheckBoxKeys?.onlySeeProduceScheduleExp?.length > 0
            ? CheckBoxKeys?.onlySeeProduceScheduleExp?.length === 1
              ? CheckBoxKeys?.onlySeeProduceScheduleExp[0]
              : null
            : null,
        orderType:
          CheckBoxKeys?.orderType && CheckBoxKeys?.orderType?.length > 0
            ? CheckBoxKeys?.orderType.length === 1
              ? CheckBoxKeys?.orderType[0]
              : null
            : null,
        fabricIntensive:
          CheckBoxKeys?.fabricIntensive && CheckBoxKeys?.fabricIntensive?.length > 0
            ? CheckBoxKeys?.fabricIntensive?.length === 1
              ? CheckBoxKeys?.fabricIntensive[0]
              : null
            : null,
        officialOrderTimeStart:
          reqParams.officialOrderTimeStart && reqParams.officialOrderTimeStart.length === 2
            ? reqParams.officialOrderTimeStart[0]
            : null,
        officialOrderTimeEnd:
          reqParams.officialOrderTimeStart && reqParams.officialOrderTimeStart.length === 2
            ? reqParams.officialOrderTimeStart[1]
            : null,
      }
    },
  })
  useEffect(() => {
    if (selectedId.current) {
      setexpandedRowKeys(selectedId.current)
    } else {
      const firstId = tableProps.dataSource?.[0]?.seqId
      firstId && setexpandedRowKeys([firstId])
    }
    settableData(tableProps?.dataSource || [])
  }, [tableProps?.dataSource])
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const handleCacheData = async () => {
    const cacheData = getCachePage()
    if (cacheData == null) {
      await form.validateFields()
      search()
      setCachePage({ ...params })
    } else {
      const { SupplierOption, UserOptions, SpuOptions, UserOptionsSelf, RootSelect, ...resetCacheData } = cacheData
      // 先重置表单再设置缓存！！！
      await form.resetFields()
      await form.setFieldsValue({
        ...resetCacheData,
      })
      setSupplierOption(SupplierOption || [])
      setUserOptions(UserOptions || [])
      setSpuOptions(SpuOptions || [])
      setUserOptionsSelf(UserOptionsSelf || [])
      reload({ ...resetCacheData })
    }
  }
  const onEditRemark = (items: any) => {
    addModal.openModal({
      ...items.purchaseProduceScheduleExtraVO,
      updateDeliveryTime: items.updateDeliveryTime,
      purchaseProduceScheduleTypeCode: items.purchaseProduceScheduleTypeCode,
      purchaseOrderCode: items.purchaseOrderCode,
      spuCode: items.spuCode,
      colorDetailName: items.colorDetailName,
      colorCode: items.colorCode,
    })
  }
  const onEditTime = (items: any) => {
    console.log(items, 'items')
    const { type, updateKey, purchaseProduceScheduleId, spuCode, purchaseOrderCode, colorDetailName } = items
    editTimeModal.openModal({
      type,
      updateKey,
      purchaseProduceScheduleId,
      spuCode,
      purchaseOrderCode,
      colorDetailName,
      planTime: type == 1 ? items.planTime : null,
      actualTime: type == 2 ? items.actualTime : null,
    })
  }
  const handleHasRead = async (items: any) => {
    console.log(items, 'items')
    const res = await trackWorkbenchHasRead({
      purchaseProduceScheduleId: items?.purchaseProduceScheduleId,
    })
    if (res.code == 200) {
      message.success('操作成功')
      reload()
    }
  }
  const onUploadFileCancel = () => {
    FormUpload.resetFields()
    setisUploadFileShow(false)
  }
  const onUploadFileOk = async () => {
    const { file } = await FormUpload.validateFields()
    setexportLoading(true)
    if (tempCode === IMPORT_FILE_ENUM.PURCHASEW_PROCESS_IMPORT) {
      const res = await importPurchaseProduceSchedule<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        FormUpload.resetFields()
      })
      if (res.code === 200) {
        importNotification(res?.data?.linkUrl)
        reload()
        onUploadFileCancel()
      }
    }
    if (tempCode === IMPORT_FILE_ENUM.PURCHASEW_DELIVERYTIME_IMPORT) {
      const res = await batchImportDeliveryTime<{ linkUrl: string }>(file).finally(() => {
        setexportLoading(false)
        reload()
        onUploadFileCancel()
        FormUpload.resetFields()
      })
      if (res.code === 200) {
        notification.open({
          type: 'success',
          message: '所有数据导入成功',
          duration: 5,
        })
      }
      if (res?.code === 820000) {
        const key = `open${Date.now()}`
        notification.open({
          type: 'warning',
          message: <div style={{ fontWeight: 500, userSelect: 'none' }}>存在导入失败的数据</div>,
          description: res?.msg,
          duration: null,
          key,
        })
      }
    }
  }
  const onSaveUser = async (rows: ITableData, isFlush: boolean) => {
    if (isFlush) {
      if (!rows.trackOrderPersonWorkId || !rows.trackOrderPerson) {
        message.warning('请选择供应链跟单后后再保存！')
        return
      }
      const res = await updatePurchaseInfo({
        id: rows.purchaseOrderId,
        trackOrderPersonWorkId: rows.trackOrderPersonWorkId,
        trackOrderPerson: rows.trackOrderPerson,
      })
      if (res.code == 200) {
        message.success('操作成功')
      }
    }
    reload()
  }
  const onEditDeliveryTime = async (items: ITableData) => {
    editTimeModal.openModal({
      ...items,
      type: 3,
    })
  }
  const onViewArrived = async (info: ITableData) => {
    const res = await getReserveInvoiceWithPurchase({
      purchaseOrderCode: info?.purchaseOrderCode,
      id: info?.purchaseOrderId,
      spuCode: info.commoditySkus && info.commoditySkus.length > 0 ? info?.spuCode : null,
      colorDetailName: info.commoditySkus && info.commoditySkus.length > 0 ? info?.colorDetailName : null,
      skuCode: info.commoditySkus && info.commoditySkus.length > 0 ? null : info?.skuCode,
    })
    if (res.code === 200) {
      TrackingArrivedModal.openModal(res?.data || [])
    }
  }
  const handleCircleChange = (type: 'week' | 'month') => {
    weekOrMonth.current = type
    getCountArrivalTracking()
  }

  // 根据类型获取本周或本月的开始和结束日期
  const getRangeByType = (type: 'week' | 'month') => {
    let start, end
    if (type === 'week') {
      start = dayjs().startOf('week').format('YYYY-MM-DD')
      end = dayjs().endOf('week').format('YYYY-MM-DD')
    } else {
      start = dayjs().startOf('month').format('YYYY-MM-DD')
      end = dayjs().endOf('month').format('YYYY-MM-DD')
    }
    return {
      requiredArrivalTimeStart: start,
      requiredArrivalTimeEnd: end,
    }
  }
  return (
    <DetailContainer className="desk_mer_wrap">
      <div style={{ marginBottom: 12, paddingBottom: progressCollapsed ? 12 : 0 }} className="desk_mer_header">
        <div className="dmh_title">
          <span className="dmh_title_main">生产信息</span>
          <span className="dmh_title_btn" onClick={() => setProgressCollapsed((v) => !v)}>
            {progressCollapsed ? '展开' : '收起'}
            {progressCollapsed ? <DownOutlined style={{ marginLeft: 4 }} /> : <UpOutlined style={{ marginLeft: 4 }} />}
          </span>
        </div>
        {!progressCollapsed ? (
          <React.Fragment>
            {isLeader && (
              <div style={{ padding: '12px 0 6px' }}>
                <span>供应链跟单：</span>
                <Select
                  placeholder="请选择供应链跟单"
                  value={leaderSelectWorkId}
                  style={{ width: 200 }}
                  showSearch={true}
                  suffixIcon={null}
                  optionFilterProp="label"
                  filterOption={false}
                  options={UserOptionsSelf}
                  onSearch={(val) => handleSearchUserSelf(val)}
                  allowClear
                  onClear={() => handleSearchUserSelf('')}
                  notFoundContent={<Empty description="请输入内容搜索" image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                  fieldNames={{ label: 'label', value: 'workId' }}
                  onChange={(_, items) => {
                    setleaderSelectWorkId(items?.workId || null)
                    const cacheData = getCachePage()
                    setCachePage({
                      ...cacheData,
                      RootSelect: items?.workId || null,
                      UserOptionsSelf,
                    })
                  }}
                ></Select>
              </div>
            )}
            <BoxGroup
              boxes={[
                {
                  key: 'a',
                  content: (
                    <>
                      <div className="boxgroup-subBox">
                        <ProcessCircle
                          title="生产计划维护情况"
                          percentage={scheduleDefendOverview.percent}
                          noplan={scheduleDefendOverview.unMaintainCount}
                          hasplan={scheduleDefendOverview.maintainCount}
                          noplantext="未维护"
                          hasplantext="已维护"
                        ></ProcessCircle>
                      </div>
                      <div className="boxgroup-subBox">
                        <ProcessPie
                          title="生产进度异常情况"
                          data={[
                            {
                              type: 'success',
                              value:
                                countProduceScheduleExp.totalNum -
                                countProduceScheduleExp.lessExpNum -
                                countProduceScheduleExp.moreExpNum,
                              label: '进度正常',
                              color: '#165DFF',
                            },
                            {
                              type: 'warning',
                              value: countProduceScheduleExp.lessExpNum,
                              label: '异常<7天',
                              color: '#FFEB3B',
                            },
                            {
                              type: 'error',
                              value: countProduceScheduleExp.moreExpNum,
                              label: '异常≥7天',
                              color: '#FF4D4F',
                            },
                          ]}
                          total={countProduceScheduleExp.totalNum}
                        />
                      </div>
                      <div className="boxgroup-subBox">
                        <ProcessCircle
                          title="到货情况"
                          percentage={countArrivalTracking.percent}
                          noplan={countArrivalTracking.arrivedNum}
                          hasplan={countArrivalTracking.shouldArriveNum}
                          noplantext="已到货"
                          hasplantext="应到货"
                          onChange={handleCircleChange}
                        ></ProcessCircle>
                      </div>
                    </>
                  ),
                  collapsedLabel: (
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
                      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                        <span>供应链</span>
                        <span>监控</span>
                      </div>
                      <img src={DeskMerLogo} alt="" style={{ width: 120, height: 120 }} />
                    </div>
                  ),
                  className: 'boxgroup-box-a',
                },
                {
                  key: 'c',
                  content: (
                    <div className="boxgroup-subBox">
                      <ToDoList workToDoMap={workToDoMap}></ToDoList>
                    </div>
                  ),
                  collapsedLabel: (
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
                      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                        <span>跟单待办</span>
                        <span style={{ visibility: 'hidden' }}>～</span>
                      </div>
                      <img src={DeskMerLogo} alt="" style={{ width: 120, height: 120 }} />
                    </div>
                  ),
                  className: 'boxgroup-box-c',
                },
                {
                  key: 'b',
                  content: (
                    <>
                      <div className="boxgroup-subBox-square">
                        <CircleRate AnnualDeliveryRate={AnnualDeliveryRate}></CircleRate>
                      </div>
                      <div className="boxgroup-subBox">
                        <ReturnTimeTable tableData={dashBoardData}></ReturnTimeTable>
                      </div>
                    </>
                  ),
                  collapsedLabel: (
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
                      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                        <span>供应链</span>
                        <span>达成</span>
                      </div>
                      <img src={DeskMerLogo} alt="" style={{ width: 120, height: 120 }} />
                    </div>
                  ),
                  className: 'boxgroup-box-b',
                },
              ]}
              defaultActiveKey="c"
            />
          </React.Fragment>
        ) : null}
      </div>
      <div className="desk_mer_header">
        <div className="dmh_title">
          <span className="dmh_title_main">生产进度</span>
        </div>
        <SearchForm
          loading={tableProps.loading}
          form={form}
          searchConfig={searchConfig({
            SupplierOption,
            handleSearchSupplier,
            classBig,
            UserOptions,
            handleSearchUser,
            SpuOptions,
            handleSearchSpu,
          })}
          onFinish={async () => {
            setCachePage({
              ...form.getFieldsValue(),
              SupplierOption,
              UserOptions,
              SpuOptions,
              current: 1,
              size: params.size,
            })
            search()
            setselectedRowKeys([])
            setselectedRows([])
          }}
          onReset={() => {
            reset()
            setCachePage({
              current: 1,
              size: 10,
              officialOrderTimeStart: defaultDateRange,
              CheckBoxKeys: { statuses: [2] },
            })
            setselectedRowKeys([])
            setselectedRows([])
          }}
          extra={
            <div>
              <div>
                <Form form={form}>
                  <Form.Item noStyle name="CheckBoxKeys">
                    <CheckBoxBatch
                      onChange={(CheckBoxKeys) => {
                        console.log(CheckBoxKeys, 'CheckBoxKeys')
                        const cacheData = getCachePage()
                        setCachePage({
                          ...cacheData,
                          CheckBoxKeys,
                          current: 1,
                        })
                        search()
                      }}
                      isLoading={tableProps.loading}
                      data={[
                        {
                          label: '采购单状态',
                          key: 'statuses',
                          options: [
                            { label: '生产中', value: 2 },
                            { label: '已完成-全部收货', value: 3 },
                            { label: '已完成-部分收货', value: 5 },
                          ],
                        },
                        {
                          label: '异常情况',
                          key: 'onlySeeProduceScheduleExp',
                          options: [
                            { label: '有异常', value: 1 },
                            { label: '无异常', value: 0 },
                          ],
                        },
                        {
                          label: '采购方式',
                          key: 'queryPurchaseTypeList',
                          options: [
                            { label: '集采', value: 0 },
                            { label: '现采', value: 1 },
                          ],
                        },
                        {
                          label: '订单类型',
                          key: 'orderType',
                          options: [
                            { label: '首单', value: 0 },
                            { label: '返单', value: 1 },
                          ],
                        },
                        {
                          label: '面料类型',
                          key: 'fabricIntensive',
                          options: [
                            { label: '集约', value: 1 },
                            { label: '非集约', value: 0 },
                          ],
                        },
                        {
                          label: '到货情况',
                          key: 'arrivalWarningStatues',
                          options: [
                            { label: '即将超时', value: 1 },
                            { label: '超时未到货', value: 2 },
                          ],
                        },
                      ]}
                    ></CheckBoxBatch>
                  </Form.Item>
                </Form>
              </div>
              <div className="table_extra_flex">
                <PermissionButton
                  permission="editDeliveryDate"
                  onClick={() => {
                    setTempcode(IMPORT_FILE_ENUM.PURCHASEW_DELIVERYTIME_IMPORT)
                    setisUploadFileShow(true)
                  }}
                  icon={<ImportOutlined />}
                  disabled={tableProps.loading}
                >
                  批量填写供应链交期
                </PermissionButton>
                <PermissionButton
                  permission="batchEditProgress"
                  onClick={() => {
                    setTempcode(IMPORT_FILE_ENUM.PURCHASEW_PROCESS_IMPORT)
                    setisUploadFileShow(true)
                  }}
                  icon={<ImportOutlined />}
                  disabled={tableProps.loading}
                >
                  批量更新生产进度
                </PermissionButton>
                <PermissionButton
                  permission="FabricConfirmTime"
                  type="primary"
                  onClick={async () => {
                    if (selectedRowKeys.length === 0) {
                      message.warning('请勾选需要操作的列表数据！')
                      return
                    } else if (selectedRowKeys.length > 1) {
                      message.warning('最多只能勾选一条列表数据！')
                      return
                    } else {
                      console.log(selectedRows, 'selectedRows')
                      const items = {
                        purchaseOrderCode: selectedRows?.[0]?.purchaseOrderCode,
                        spuCode: selectedRows?.[0]?.spuCode,
                        colorCode: selectedRows?.[0]?.colorCode,
                        colorDetailName: selectedRows?.[0]?.colorDetailName,
                        id: selectedRows?.[0]?.produceScheduleDtlVOS?.[0]?.purchaseProduceScheduleExtraVO?.id || null,
                        scheduleType: 1,
                      }
                      console.log(items, 'items')
                      const res = await trackWorkbenchConfirmTime({ ...items, confirmTime: 1 })
                      if (res.code == 200) {
                        message.success('操作成功')
                        reload()
                        setselectedRowKeys([])
                        setselectedRows([])
                      }
                    }
                  }}
                  disabled={tableProps.loading}
                >
                  <Tooltip title="确认后面料到厂时间将被锁定，不再支持修改">确认面料到厂时间</Tooltip>
                </PermissionButton>
              </div>
            </div>
          }
        ></SearchForm>
      </div>

      <CustomTable
        stripe={false}
        isAutoScrollY={false}
        scroll={{ x: '100%', y: '66vh' }}
        {...tableProps}
        columns={useIndexColumns({
          navigate,
          tableData,
          settableData,
          UserOptions: UserOptionsW,
          handleSearchUser: handleSearchUserW,
          setUserOptions: setUserOptionsW,
          onSaveUser,
          onEditDeliveryTime,
          onViewArrived,
          EditTrackOrderPerson: buttonCodeList.includes('EditTrackOrderPerson'),
          isRoot,
        })}
        rowSelection={{
          selectedRowKeys,
          onChange(selectedRowKeys, selectedRows) {
            setselectedRowKeys(selectedRowKeys)
            setselectedRows(selectedRows)
          },
        }}
        rowKey={(rows) => rows?.seqId}
        expandable={{
          expandedRowKeys,
          onExpandedRowsChange: (keys: any) => {
            const selectedItem = keys?.[keys?.length - 1] || null
            selectedId.current = selectedItem
            setexpandedRowKeys(selectedItem ? [selectedItem] : [])
          },
          expandedRowRender: (record) => {
            return (
              <TimeLineScroll
                onEditRemark={onEditRemark}
                onEditTime={onEditTime}
                handleHasRead={handleHasRead}
                timelineData={
                  record?.produceScheduleDtlVOS?.map((item: any) => {
                    return {
                      ...record,
                      ...item,
                      purchaseProduceScheduleId: record.purchaseProduceScheduleId,
                    }
                  }) || []
                }
              ></TimeLineScroll>
            )
          },

          rowExpandable: (record) => record?.produceScheduleDtlVOS?.length > 0,
        }}
      ></CustomTable>

      <Modal
        width={800}
        title="生产进度备注"
        open={addModal.open}
        maskClosable
        onCancel={addModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={addModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={addModal.confirmLoading}
                onClick={() => {
                  addModal.handleSubmit((vals) => {
                    const {
                      purchaseProduceScheduleTypeCode,
                      purchaseOrderCode,
                      spuCode,
                      colorDetailName,
                      colorCode,
                      id,
                    } = addModal.currentRecord
                    return saveScheduleExtraReq({
                      ...vals,
                      id,
                      scheduleType: purchaseProduceScheduleTypeCode,
                      purchaseOrderCode,
                      spuCode,
                      colorDetailName,
                      colorCode,
                    })
                  })
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div className="desk_mer_remark_modal">
          <EditFormVertical
            editConfig={useEditConfig({ DICTDATA, form: addModal.form, impactDeliveryTime })}
            form={addModal.form}
            initialValues={{ impactDeliveryTime: 0 }}
          />
        </div>
      </Modal>
      <Modal
        title={
          editTimeModal.currentRecord?.type == 1
            ? '计划时间'
            : editTimeModal.currentRecord?.type == 2
            ? '实际时间'
            : editTimeModal.currentRecord?.type == 3
            ? '供应链交期'
            : null
        }
        open={editTimeModal.open}
        maskClosable
        onCancel={editTimeModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={editTimeModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={editTimeModal.confirmLoading}
                onClick={() => {
                  const { updateKey, purchaseProduceScheduleId, type, spuCode, purchaseOrderCode, colorDetailName } =
                    editTimeModal.currentRecord
                  if (type != 3) {
                    return editTimeModal.handleSubmit((vals) =>
                      updateScheduleTime([
                        {
                          [updateKey]: type == 1 ? vals.planTime : type == 2 ? vals.actualTime : null,
                          id: purchaseProduceScheduleId,
                          spuCode,
                          purchaseOrderCode,
                          colorDetailName,
                        },
                      ]),
                    )
                  } else {
                    return editTimeModal.handleSubmit((vals) =>
                      updatePurchaseInfo({
                        deliveryTime: vals.updateDeliveryTime,
                        id: editTimeModal.currentRecord?.purchaseOrderId,
                      }),
                    )
                  }
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              name: 'planTime',
              label: '计划时间',
              type: 'FixedDatePicker',
              placeholder: '请选择计划时间',
              config: {
                customFormat: 'YYYY-MM-DD',
              },
              rules: [
                {
                  required: true,
                  message: '请选择计划时间',
                },
              ],
              hidden: editTimeModal.currentRecord?.type != 1,
            },
            {
              name: 'actualTime',
              label: '实际时间',
              type: 'FixedDatePicker',
              placeholder: '请选择实际时间',
              config: {
                customFormat: 'YYYY-MM-DD',
              },
              rules: [
                {
                  required: true,
                  message: '请选择实际时间',
                },
              ],
              hidden: editTimeModal.currentRecord?.type != 2,
            },
            {
              name: 'updateDeliveryTime',
              label: '供应链交期',
              type: 'FixedDatePicker',
              placeholder: '请选择供应链交期',
              config: {
                customFormat: 'YYYY-MM-DD',
                minDate: editTimeModal.currentRecord?.requiredArrivalTime
                  ? dayjs(editTimeModal.currentRecord?.requiredArrivalTime).subtract(10, 'day')
                  : undefined,
                maxDate: editTimeModal.currentRecord?.requiredArrivalTime
                  ? dayjs(editTimeModal.currentRecord?.requiredArrivalTime)
                  : undefined,
              },
              rules: [
                {
                  required: true,
                  message: '请选择供应链交期',
                },
                {
                  validator: (_: any, value: any) =>
                    TwoDateVerifyCanEqual(
                      _,
                      _,
                      value,
                      editTimeModal.currentRecord?.requiredArrivalTime,
                      '供应链交期不能晚于要求到货日期',
                    ),
                },
              ],
              hidden: editTimeModal.currentRecord?.type != 3,
            },
          ]}
          form={editTimeModal.form}
        />
      </Modal>
      <ImportFileModal
        loading={exportLoading}
        open={isUploadFileShow}
        onCancel={onUploadFileCancel}
        onOk={onUploadFileOk}
        form={FormUpload}
        tempCode={tempCode}
      ></ImportFileModal>
      <Modal
        title="到货批次"
        footer={null}
        open={TrackingArrivedModal.open}
        maskClosable
        onCancel={TrackingArrivedModal.closeModal}
        width={1200}
        wrapClassName="tracking_modal_self_wrap"
      >
        <CustomTable
          bordered
          columns={useArrivalColumns()}
          dataSource={TrackingArrivedModal?.currentRecord || []}
          pagination={false}
          rowKey={(rows) => rows?.reserveInvoiceCode}
          scroll={{ x: 1000 }}
        />
      </Modal>
    </DetailContainer>
  )
}

export default Index
